import { NextRequest, NextResponse } from 'next/server';
import UserModel from '@/models/user';
import { authMiddleware } from '@/utils/auth';

export async function GET(request: NextRequest) {
  try {
    // 获取查询参数
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const limit = parseInt(url.searchParams.get('limit') || '10');
    const companyId = url.searchParams.get('company_id');
    const status = url.searchParams.get('status') || 'active';
    const own = url.searchParams.get('own') === 'true'; // 是否只获取自己发布的职位

    console.log('获取招聘列表请求参数:', { page, limit, companyId, status, own });

    // 计算偏移量
    const offset = (page - 1) * limit;

    // 构建查询条件
    let whereClause = 'WHERE jp.status = ?';
    const queryParams: any[] = [status];

    if (companyId) {
      whereClause += ' AND jp.company_id = ?';
      queryParams.push(companyId);
    }

    // 如果请求获取自己发布的职位，需要进行身份验证
    if (own) {
      const authResult = await authMiddleware(request);
      if (authResult instanceof NextResponse) {
        return authResult; // 返回错误响应
      }

      const userId = authResult.id;
      console.log('获取用户自己发布的职位, 用户ID:', userId);

      // 添加发布者条件
      whereClause += ' AND jp.created_by = ?';
      queryParams.push(userId);
    }

    // 查询总数
    const [countResult] = await UserModel.query<any[]>(
      `SELECT COUNT(*) as total
       FROM job_positions jp
       ${whereClause}`,
      queryParams
    );

    const total = countResult[0]?.total || 0;
    console.log('查询到的职位总数:', total);

    // 查询职位列表
    const countSql = `SELECT COUNT(*) as total FROM job_positions jp ${whereClause}`;
    console.log('总数查询SQL:', countSql, '参数:', queryParams);

    // 使用直接插入的方式构建SQL查询，避免参数化LIMIT和OFFSET
    const jobsSql = `SELECT jp.id, jp.company_id, jp.title, jp.description, jp.requirements, jp.salary_range,
              jp.location, jp.job_type, jp.experience, jp.education, jp.status, jp.created_by,
              jp.application_count,
              DATE_FORMAT(jp.created_at, '%Y-%m-%d %H:%i:%s') as created_at,
              DATE_FORMAT(jp.updated_at, '%Y-%m-%d %H:%i:%s') as updated_at,
              c.name as company_name, c.logo as company_logo, c.industry as company_industry,
              c.size as company_size
       FROM job_positions jp
       LEFT JOIN companies c ON jp.company_id = c.id
       ${whereClause}
       ORDER BY jp.created_at DESC
       LIMIT ${limit} OFFSET ${offset}`;

    console.log('职位列表查询SQL:', jobsSql, '参数:', queryParams);

    // 执行查询
    const [jobs] = await UserModel.query<any[]>(jobsSql, queryParams);

    console.log('查询到的职位数量:', jobs.length);
    if (jobs.length > 0) {
      console.log('第一个职位信息:', {
        id: jobs[0].id,
        title: jobs[0].title,
        company_id: jobs[0].company_id,
        company_name: jobs[0].company_name,
        application_count: jobs[0].application_count,
        application_count_type: typeof jobs[0].application_count
      });
    }

    // 返回结果
    return NextResponse.json({
      jobs,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取招聘列表失败:', error);
    return NextResponse.json(
      { error: '获取招聘列表失败' },
      { status: 500 }
    );
  }
}
